<?php
namespace app\admin\controller;

use think\Db;
use think\Request;
class Product extends Common
{

    /**
     * 列表
     */
    public function index(){
        if(Request::instance()->isAjax()){
            return \app\common\model\Product::getList([]);
        }
        return view('');
    }


    /**
     * 创建
     */
    public function create(){
        $this->view->engine->layout('common/iframe');
        return view('');
    }


    /**
     * 编辑
     */
    public function edit(){
        try{
            $this->view->engine->layout('common/iframe');
            $id = input('id');
            $role = \app\common\model\Product::get($id);
            if(empty($role)){
                exception('产品信息不存在');
            }
            return view('create',['data'=>$role]);
        }catch (\Exception $e) {
            return view('common/error',['msg' => $e->getMessage()]);
        }
    }


    /**
     * 删除
     */
    public function delete(){
        try{
            $id = input('id');
            $role = \app\common\model\Product::destroy($id);
            if ($role){
                return ['code'=>'0','msg'=>'删除成功'];
            }else{
                return ['code'=>'1','msg'=>'删除成功'];
            }
        }catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => $exception->getMessage(), 'data' => []]);
        }
    }


    /**
     * 保存
     */
    public function save(){
        try{
            $data = input('post.','','trim');

            Db::startTrans();
            if(isset($data['id']) && !empty($data['id'])){
                $role = \app\common\model\Product::get(['id'=>$data['id']]);
                if($role->force()->update($data) === false){
                    exception('保存失败');
                }
            }else{
                $role = new \app\common\model\Product($data);
                if(!$role->force()->save($data)){
                    exception('保存失败');
                }
            }
            Db::commit();
            return  json(['code'=>0,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }

    }

}
